package cn.kgc.news.contriller;
import cn.kgc.news.pojo.News;
import cn.kgc.news.service.NewsService;
import cn.kgc.news.service.impl.NewsSerivceImpl;
import cn.kgc.news.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
@WebServlet(name = "NewsServlet", urlPatterns = "/newsServlet")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NewsService newsService = new NewsSerivceImpl();
        String action = request.getParameter("action");
        PrintWriter out=response.getWriter();

        //查询方法
        if ("select".equals(action)) {
//            List<News> list = newsService.getNewsList();
//            StringBuffer jsonNews=new StringBuffer("[");
//            for(int i=0;i<list.size();i++){
//                jsonNews.append("{\"id\":"+list.get(i).getId()+",\"title\":\""+list.get(i).getTitle()+"\",\"author\":\""+list.get(i).getAuthor()+"\",\"createDate\":\""+list.get(i).getCreateDate()+"\"}");
//                if(i!=list.size()-1){
//                    jsonNews.append(",");
//                }
//            }
//            jsonNews.append("]");
//            out.print(jsonNews.toString());
//        }else if ("select1".equals(action)){
//            List<News> newsList=newsService.getNewsList();
//            StringBuffer stringBuffer=new StringBuffer("");
//            for (int i = 0; i <newsList.size() ; i++) {
//                stringBuffer.append("<tr><td>"+newsList.get(i).getTitle()+"</td><td>"+newsList.get(i).getAuthor()+"</td><td>"+newsList.get(i).getCreateDate()+"</td><td>"+"<a href=\"newsDetailUpdateSimple.jsp?id="+newsList.get(i).getId()+"\">编辑</a>" +
//                        "<input type='button' value='删除'  onclick='delNewsById("+newsList.get(i).getId()+")'/>"+"</td></tr>");
//            }
//            out.print(stringBuffer);
        }else if ("select2".equals(action)){
//            List<News> newsList=newsService.getNewsList();
//            request.setAttribute("list",newsList);
//            request.getRequestDispatcher("/jsp/showNews.jsp").forward(request,response);
        }else if ("select3".equals(action)){
            PageSupport pageSupport=new PageSupport();
            int currentPage=Integer.parseInt(request.getParameter("currentPage"));  //接受当前页码的值
            int pageSize=Integer.parseInt(request.getParameter("pageSize"));    //接受每页的条数
            int cId=Integer.parseInt(request.getParameter("categoryId"));   //接受新闻分类的值
            String tit=request.getParameter("title");   //接受用户输入的标题
            int totalCount=newsService.getTotalCount(cId,tit);  //调用方法获得总页数
            pageSupport.setTotalCount(totalCount);
            pageSupport.setCurrentPage(currentPage);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalPages(pageSupport.getTotalPages());
            List<News> list = newsService.getNewsList(currentPage, pageSize,cId,tit);
            pageSupport.setList(list);
            String jsonNews=JSON.toJSONStringWithDateFormat(pageSupport,"yyyy-MM-dd");
            out.print(jsonNews);
        }
        else if ("add".equals(action)) {
            String categoryId=request.getParameter("categoryId");
            String summary=request.getParameter("summary");
            String content=request.getParameter("content");
            String author=request.getParameter("author");
//            String picPath=request.getParameter("picPath");
            String title=request.getParameter("title");
            News news=new News();
            news.setCategoryId(Integer.parseInt(categoryId));
            news.setAuthor(author);
            news.setContent(content);
            news.setSummary(summary);
            news.setTitle(title);
            news.setCreateDate( new Date());
            news.setModifyDate(new Date());
//            news.setPicPath(picPath);
            int i = newsService.insertNews(news);
            boolean flag = false;
            if (i > 0) {
                flag = true;
            }
            String data="{\"flag\":\""+flag+"\"}";
            out.print(data);
            //request.getRequestDispatcher("/newsServlet?action=select&flag="+flag).forward(request,response);
//            response.sendRedirect("/newsServlet?action=select&flag=" + flag);
        } else if ("delete".equals(action)) {
            int n = Integer.parseInt(request.getParameter("id"));
            int i = newsService.deleteNews(n);
            boolean flag = false;
            if (i > 0) {
                flag = true;
            }

            String data="{\"flag\":\""+flag+"\"}";
            out.print(data);
        } else if ("getNewsById".equals(action)) {
            int i = Integer.parseInt(request.getParameter("id"));
            News news = newsService.getNewsById(i);
            String newsJson=JSON.toJSONString(news);
            out.print(newsJson);
        } else if ("update".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            int categoryId = Integer.parseInt(request.getParameter("categoryId"));
            String summary = request.getParameter("summary");
            String content = request.getParameter("content");
            String author = request.getParameter("author");
            String picPath = request.getParameter("picPath");
            String title = request.getParameter("title");
            News news = new News();
            news.setId(id);
            news.setCategoryId(categoryId);
            news.setAuthor(author);
            news.setContent(content);
            news.setSummary(summary);
            news.setTitle(title);
            news.setCreateDate(new Date());
            news.setModifyDate(new Date());
            news.setPicPath(picPath);
            int i = newsService.updateNews(news);
            boolean flag = false;
            if (i > 0) {
                flag = true;
            }
            String data="{\"flag\":\""+flag+"\"}";
            out.print(data);
        } else if ("getDetailById".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            News news = newsService.getNewsById(id);
            request.setAttribute("news", news);
            request.getRequestDispatcher("jsp/newsDetailView.jsp").forward(request, response);
        }
        out.flush();
        out.close();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
